package it.xiuxian.homepage.activity

import android.animation.ObjectAnimator
import android.os.Build
import android.util.Log
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.LinearLayout
import android.widget.RelativeLayout
import androidx.annotation.RequiresApi
import androidx.constraintlayout.widget.ConstraintLayout
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.bytedance.sdk.openadsdk.*
import it.xiuxian.homepage.R
import it.xiuxian.homepage.bean.WorkBean
import it.xiuxian.homepage.databinding.HomepageWorkBinding
import it.xiuxian.homepage.presenter.WorkActivityPresenter
import it.xiuxian.lib.base.App
import it.xiuxian.lib.base.ArouterAddress
import it.xiuxian.lib.base.BaseActivity
import it.xiuxian.lib.utils.*
import kotlinx.android.synthetic.main.homepage_work.*

@Route(path = ArouterAddress.WORKACTIVITY)
class WorkActivity:BaseActivity<WorkActivityPresenter>(){
   lateinit var binding:HomepageWorkBinding
    private var flag1 = true
    private var flag2 = true
    private var flag3 = true
    private var flag4 = true
    private var flag5 = true
   var list = ArrayList<Boolean>()
    override val layoutId: Int
        get() = R.layout.homepage_work
    override val presenter: WorkActivityPresenter
        get() = WorkActivityPresenter()

    override fun initView(){
        binding =  getViewDataBinding<HomepageWorkBinding>()
          /*  var alp= ObjectAnimator.ofFloat(binding.imageQiu5,"alpha",1.0f,0.3f,1.0f)
            alp.setDuration(1000)
            alp.startDelay = 300
            alp.start()*/




        // binding.imageQiu1.startAnimation(AnimationUtils.loadAnimation(this,R.anim.animator_translate))
        ImageUtil.setOriginImage(R.mipmap.homepage_shou,binding.imageshou)
        binding.cons.setOnClickListener { finish() }
        for(i in 0 until 5){
            list.add(true)
        }
        //binding.cons.setPadding(0,DensityUtil.px2dip(App.INSTANCE!!.applicationContext),0,0)
        (binding.cons.layoutParams as LinearLayout.LayoutParams).setMargins(0,DensityUtil.getStatusPix(App.INSTANCE.applicationContext)+5,0,0)
       // binding.cons.layoutParams = DensityUtil.setStatusMargin(App.INSTANCE!!.applicationContext)
        ImageUtil.setOriginImage(R.mipmap.homepage_dongren1,binding.image)
        binding.tvQulingqu.setOnClickListener{
            if(Utils.isFastClick()){
                initGuanggao()
            }
        }
        mPresenter!!.getList()
    }
fun setVisible(ab:ArrayList<Boolean>){
    binding.imageQiu4.visibility=if(ab[0]) View.VISIBLE else View.INVISIBLE
    binding.imageshou.visibility=if(ab[0]) View.VISIBLE else View.INVISIBLE
    binding.imageQiu1.visibility=if(ab[1]) View.VISIBLE else View.INVISIBLE
    binding.imageQiu2.visibility=if(ab[2]) View.VISIBLE else View.INVISIBLE
    binding.imageQiu3.visibility=if(ab[3]) View.VISIBLE else View.INVISIBLE
    binding.imageQiu5.visibility=if(ab[4]) View.VISIBLE else View.INVISIBLE
}
    @RequiresApi(Build.VERSION_CODES.M)
    fun setUI(data: WorkBean){
       // ToastUtil.showShort("我进来了")
        binding.tvNumkan.setText(data.dayworkmoney)
        binding.imageQiu1.setText(data.dayworkmoney)
        binding.imageQiu2.setText(data.dayworkmoney)
        binding.imageQiu3.setText(data.dayworkmoney)
        binding.imageQiu4.setText(data.dayworkmoney)
        binding.imageQiu5.setText(data.dayworkmoney)
        binding.tvNumkan1.setText(data.dayworkmoney)
        binding.tvRenwu.setText("看视频赚贡献值"+data.dayworknum+"/"+data.maxdayworknum)
        if(!flag1){
            binding.imageQiu1.visibility = View.INVISIBLE
        }
        if(!flag2){
            binding.imageQiu2.visibility = View.INVISIBLE
        }
        if(!flag3){
            binding.imageQiu3.visibility = View.INVISIBLE
        }
        if(!flag4){
            binding.imageQiu4.visibility = View.INVISIBLE
            binding.imageshou.visibility = View.INVISIBLE
        }
        if(!flag5){
            binding.imageQiu5.visibility = View.INVISIBLE
        }
        var i=0
        for(t in 0 until 5){
            if(!list[t]){
                i += 1
            }
        }
        if(i==data.dayworknum.toInt()){
            if(data.dayworknum.equals(data.maxdayworknum)){
               // ToastUtil.showShort("我进来了")
                binding.tvQulingqu.setText("已领完")
                binding.tvQulingqu.isClickable = false
                binding.tvXiaoling.setText("已领完")
                binding.tvXiaoling.isClickable = false
            }else{
                binding.tvQulingqu.setText("去领取")
                binding.tvQulingqu.isClickable = true
                binding.tvXiaoling.setText("去领取")
                binding.tvXiaoling.isClickable = true
            }
            return
        }
        if(data.dayworknum.toInt()>0){
            for(i in 0 until (data.dayworknum.toInt()-i)){
             for(t in 0 until 5){
                 if(list[t]){
                     list[t] = false
                     break }
             }

            }
        }
       // Log.e("mywork",list.toString())
        setVisible(list)
        if(data.dayworknum.equals(data.maxdayworknum)){
           // ToastUtil.showShort("我进来了")
            binding.tvQulingqu.setText("已领完")
            binding.tvQulingqu.isClickable = false
            binding.tvXiaoling.setText("已领完")
            binding.tvXiaoling.isClickable = false
        }else{
            binding.tvQulingqu.setText("去领取")
            binding.tvQulingqu.isClickable = true
            binding.tvXiaoling.setText("去领取")
            binding.tvXiaoling.isClickable = true
        }
        /*for(){

        }*/
      /*  binding.tvYilingqu.text = data.dayworknum+"/"+data.maxdayworknum
        if(data.dayworknum==data.maxdayworknum){
            binding.btYiling.text = "已领取"
            binding.btYiling.background = getDrawable(R.drawable.lib_shape_corner10)
            binding.btYiling.setTextColor(getColor(R.color.libSelect))
            binding.btYiling.isEnabled = false
            binding.btYiling.isClickable = false
        }else{
            binding.btYiling.text = "领取奖励"
            binding.btYiling.background = getDrawable(R.drawable.lib_shape_corner_blue)
            binding.btYiling.setTextColor(getColor(R.color.libTextWhite))
            binding.btYiling.isEnabled = true
            binding.btYiling.isClickable = true
        }*/

    }

    fun updateUI(data: String){
            ToastUtil.showShort(data)
            mPresenter!!.getList()
    }
    private var status = true
    private var get= false
    override fun initEvent(){
        binding.llKan.setOnClickListener{
            if(Utils.isFastClick()){
            ARouter.getInstance().build(ArouterAddress.QIANDAOACTIVITY).navigation()
        }}
        binding.tvXiaoling.setOnClickListener{
            if(Utils.isFastClick()){
                initGuanggao()
            }
        }
        binding.imageQiu1.setOnClickListener {
            if(Utils.isFastClick()){
                initGuanggao()
                flag1 = false
            }

        }
        binding.imageQiu2.setOnClickListener {
            if(Utils.isFastClick()){
                initGuanggao()
                flag2 = false
                // binding.imageQiu2.visibility = View.INVISIBLE
                list[2] =false
            }

        }
        binding.imageQiu3.setOnClickListener {
            if(Utils.isFastClick()){
                initGuanggao()
                flag3 = false
                // binding.imageQiu3.visibility = View.INVISIBLE
                list[3] =false
            }

        }
        binding.imageQiu4.setOnClickListener {
            if(Utils.isFastClick()){
                initGuanggao()
                flag4 = false
                //  binding.imageQiu4.visibility = View.INVISIBLE

                list[0] =false
            }

        }
        binding.imageQiu5.setOnClickListener{
            if(Utils.isFastClick()){
                initGuanggao()
                flag5 = false
                // binding.imageQiu5.visibility = View.INVISIBLE
                list[4] =false
            }

        }
        binding.imagePai.setOnClickListener {
            ARouter.getInstance().build(ArouterAddress.PAIHANGBANGACTIVITY).navigation()
        }
        binding.imageGong.setOnClickListener {
            ARouter.getInstance().build(ArouterAddress.MYWALLETACTIVITY).navigation()
        }
    }
    private var mTTAdNative: TTAdNative? = null
    private var mHorizontalCodeId: String? = null
    private var mVerticalCodeId: String? = null
    private var mIsExpress = false //是否请求模板广告
    private  val TAG = "HomePageFragment"
    private var mIsLoaded = false //视频是否加载完成
    private var mttRewardVideoAd: TTRewardVideoAd? = null
    private var mHasShowDownloadActive = false
    fun initGuanggao(){
        //step1:初始化sdk
        val ttAdManager = TTAdManagerHolder.get()
        //step2:(可选，强烈建议在合适的时机调用):申请部分权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题。
        //step2:(可选，强烈建议在合适的时机调用):申请部分权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题。
        TTAdManagerHolder.get().requestPermissionIfNecessary(this)
        //step3:创建TTAdNative对象,用于调用广告请求接口

        //step3:创建TTAdNative对象,用于调用广告请求接口
        mTTAdNative = ttAdManager.createAdNative(this.applicationContext)
        getExtraInfo()
    }
    private fun getExtraInfo(){
        val intent = intent?: return
        mHorizontalCodeId = intent.getStringExtra("horizontal_rit")
        mVerticalCodeId = intent.getStringExtra("vertical_rit")
        mIsExpress = intent.getBooleanExtra("is_express", false)
        loadAd("947626021", TTAdConstant.VERTICAL)
    }
fun showAd(){
    if (mttRewardVideoAd != null) {
        //step6:在获取到广告后展示,强烈建议在onRewardVideoCached回调后，展示广告，提升播放体验
        //该方法直接展示广告
//                    mttRewardVideoAd.showRewardVideoAd(RewardVideoActivity.this);

        //展示广告，并传入广告展示的场景
        mttRewardVideoAd!!.showRewardVideoAd(
            this,
            TTAdConstant.RitScenes.CUSTOMIZE_SCENES,
            "scenes_test"
        )
        mttRewardVideoAd = null
    } else {
       // TToast.show(this, "请先加载广告")
    }
}
    private fun loadAd(mVerticalCodeId: String?, vertical: Int){
        //step4:创建广告请求参数AdSlot, 具体参数含义参考文档


        //step4:创建广告请求参数AdSlot,具体参数含义参考文档
        val adSlot: AdSlot
        adSlot = if (mIsExpress) {
            //个性化模板广告需要传入期望广告view的宽、高，单位dp，
            AdSlot.Builder()
                .setCodeId(mVerticalCodeId) //此次加载广告的用途是实时加载，当用来作为缓存时，请使用：TTAdLoadType.LOAD
                .setAdLoadType(TTAdLoadType.LOAD) //模板广告需要设置期望个性化模板广告的大小,单位dp,激励视频场景，只要设置的值大于0即可
                .setExpressViewAcceptedSize(500f, 500f)
                .build()
        } else {
            //模板广告需要设置期望个性化模板广告的大小,单位dp,代码位是否属于个性化模板广告，请在穿山甲平台查看
            AdSlot.Builder() //此次加载广告的用途是实时加载，当用来作为缓存时，请使用：TTAdLoadType.LOAD
                .setAdLoadType(TTAdLoadType.LOAD)
                .setCodeId(mVerticalCodeId)
                .build()
        }
        //step5:请求广告

        //step5:请求广告
        mTTAdNative!!.loadRewardVideoAd(adSlot, object : TTAdNative.RewardVideoAdListener {
            override fun onError(code: Int, message: String) {
                Log.e(
                    TAG,
                    "Callback --> onError: $code, $message"
                )
                // TToast.show(this, message)
            }

            //视频广告加载后，视频资源缓存到本地的回调，在此回调后，播放本地视频，流畅不阻塞。
            override fun onRewardVideoCached() {
                Log.e(
                    TAG,
                    "Callback --> onRewardVideoCached"
                )
                mIsLoaded = true
                //  TToast.show(this, "Callback --> rewardVideoAd video cached")
            }

            override fun onRewardVideoCached(ad: TTRewardVideoAd) {
                Log.e(
                    TAG,
                    "Callback --> onRewardVideoCached"
                )
                mIsLoaded = true
                // TToast.show(this, "Callback --> rewardVideoAd video cached")
                showAd()
                // ad.showRewardVideoAd(RewardVideoActivity.this, TTAdConstant.RitScenes.CUSTOMIZE_SCENES, "scenes_test");
            }

            //视频广告的素材加载完毕，比如视频url等，在此回调后，可以播放在线视频，网络不好可能出现加载缓冲，影响体验。
            override fun onRewardVideoAdLoad(ad: TTRewardVideoAd){
                Log.e(
                    TAG,
                    "Callback --> onRewardVideoAdLoad"
                )
                /*  TToast.show(
                    this,
                    "rewardVideoAd loaded 广告类型：" + getAdType(ad.rewardVideoAdType)
                )*/
                mIsLoaded = false
                mttRewardVideoAd = ad
                mttRewardVideoAd!!.setRewardAdInteractionListener(object :
                    TTRewardVideoAd.RewardAdInteractionListener{
                    override fun onAdShow(){
                        Log.d(
                            TAG,
                            "Callback --> rewardVideoAd show"
                        )
                        //TToast.show(this, "rewardVideoAd show")
                    }

                    override fun onAdVideoBarClick(){
                        Log.d(
                            TAG,
                            "Callback --> rewardVideoAd bar click"
                        )
                        // TToast.show(this, "rewardVideoAd bar click")
                    }

                    override fun onAdClose(){
                        Log.d(
                            TAG,
                            "Callback --> rewardVideoAd close"
                        )
                        // TToast.show(this, "rewardVideoAd close")
                    }

                    //视频播放完成回调
                    override fun onVideoComplete(){
                        Log.d(
                            TAG,
                            "Callback --> rewardVideoAd complete"
                        )
                        //  TToast.show(this, "rewardVideoAd complete")
                    }

                    override fun onVideoError(){
                        Log.e(
                            TAG,
                            "Callback --> rewardVideoAd error"
                        )
                        // TToast.show(this, "rewardVideoAd error")
                    }

                    //视频播放完成后，奖励验证回调，rewardVerify：是否有效，rewardAmount：奖励梳理，rewardName：奖励名称
                    override fun onRewardVerify(
                        rewardVerify: Boolean,
                        rewardAmount: Int,
                        rewardName: String,
                        errorCode: Int,
                        errorMsg: String
                    ) {
                        if (rewardVerify) {
                            mPresenter!!.submit()
                        }
                        /* val logString = "verify:" + rewardVerify + " amount:" + rewardAmount +
                                " name:" + rewardName + " errorCode:" + errorCode + " errorMsg:" + errorMsg
                        Log.e(
                            TAG,
                            "Callback --> $logString"
                        )
                        TToast.show(this, logString)*/
                    }

                    override fun onSkippedVideo(){
                        Log.e(
                            TAG,
                            "Callback --> rewardVideoAd has onSkippedVideo"
                        )
                        // TToast.show(this, "rewardVideoAd has onSkippedVideo")
                    }
                })
                mttRewardVideoAd!!.setRewardPlayAgainInteractionListener(object :
                    TTRewardVideoAd.RewardAdInteractionListener{
                    override fun onAdShow() {
                        Log.d(
                            TAG,
                            "Callback --> rewardPlayAgain show"
                        )
                        // TToast.show(this, "rewardVideoAd show")
                    }

                    override fun onAdVideoBarClick() {
                        Log.d(
                            TAG,
                            "Callback --> rewardPlayAgain bar click"
                        )
                        // TToast.show(this, "rewardVideoAd bar click")
                    }

                    override fun onAdClose(){
                        Log.d(
                            TAG,
                            "Callback --> rewardPlayAgain close"
                        )
                        //  TToast.show(this, "rewardVideoAd close")
                    }

                    //视频播放完成回调
                    override fun onVideoComplete(){
                        Log.d(
                            TAG,
                            "Callback --> rewardPlayAgain complete"
                        )
                        // TToast.show(this, "rewardVideoAd complete")
                    }

                    override fun onVideoError(){
                        Log.e(
                            TAG,
                            "Callback --> rewardPlayAgain error"
                        )
                        //  TToast.show(this, "rewardVideoAd error")
                    }

                    //视频播放完成后，奖励验证回调，rewardVerify：是否有效，rewardAmount：奖励梳理，rewardName：奖励名称
                    override fun onRewardVerify(
                        rewardVerify: Boolean,
                        rewardAmount: Int,
                        rewardName: String,
                        errorCode: Int,
                        errorMsg: String
                    ) {
                        val logString =
                            "rewardPlayAgain verify:" + rewardVerify + " amount:" + rewardAmount +
                                    " name:" + rewardName + " errorCode:" + errorCode + " errorMsg:" + errorMsg
                        Log.e(
                            TAG,
                            "Callback --> $logString"
                        )
                        // TToast.show(this, logString)
                    }

                    override fun onSkippedVideo(){
                        Log.e(
                            TAG,
                            "Callback --> rewardPlayAgain has onSkippedVideo"
                        )
                        //   TToast.show(this, "rewardVideoAd has onSkippedVideo")
                    }
                })
                mttRewardVideoAd!!.setDownloadListener(object : TTAppDownloadListener{
                    override fun onIdle() {
                        mHasShowDownloadActive = false
                    }

                    override fun onDownloadActive(
                        totalBytes: Long,
                        currBytes: Long,
                        fileName: String,
                        appName: String
                    ){
                        Log.d(
                            "DML",
                            "onDownloadActive==totalBytes=$totalBytes,currBytes=$currBytes,fileName=$fileName,appName=$appName"
                        )
                        if (!mHasShowDownloadActive) {
                            mHasShowDownloadActive = true
                            //   TToast.show(this, "下载中，点击下载区域暂停", Toast.LENGTH_LONG)
                        }
                    }

                    override fun onDownloadPaused(
                        totalBytes: Long,
                        currBytes: Long,
                        fileName: String,
                        appName: String
                    ){
                        Log.d(
                            "DML",
                            "onDownloadPaused===totalBytes=$totalBytes,currBytes=$currBytes,fileName=$fileName,appName=$appName"
                        )
                        // TToast.show(this, "下载暂停，点击下载区域继续", Toast.LENGTH_LONG)
                    }

                    override fun onDownloadFailed(
                        totalBytes: Long,
                        currBytes: Long,
                        fileName: String,
                        appName: String
                    ){
                        Log.d(
                            "DML",
                            "onDownloadFailed==totalBytes=$totalBytes,currBytes=$currBytes,fileName=$fileName,appName=$appName"
                        )
                        // TToast.show(this, "下载失败，点击下载区域重新下载", Toast.LENGTH_LONG)
                    }

                    override fun onDownloadFinished(
                        totalBytes: Long,
                        fileName: String,
                        appName: String
                    ) {
                        Log.d(
                            "DML",
                            "onDownloadFinished==totalBytes=$totalBytes,fileName=$fileName,appName=$appName"
                        )
                        //  TToast.show(this, "下载完成，点击下载区域重新下载", Toast.LENGTH_LONG)
                    }

                    override fun onInstalled(fileName: String, appName: String){
                        Log.d("DML", "onInstalled==,fileName=$fileName,appName=$appName")
                        //  TToast.show(this, "安装完成，点击下载区域打开", Toast.LENGTH_LONG)
                    }
                })
            }
        })
    }
}